package com.itheima.controller;


import com.itheima.dto.UserLoginDTO;
import com.itheima.properties.JwtProperties;
import com.itheima.result.Result;
import com.itheima.service.IUserService;
import com.itheima.ship.po.User;
import com.itheima.utils.JwtUtil;
import com.itheima.vo.ShipVO;
import com.itheima.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.security.auth.login.LoginException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 微信用户 前端控制器
 * </p>
 *
 * @author 郑哥
 * @since 2024-05-13
 */
@RestController
@RequestMapping("/user")
@Api(tags = "微信登录相关接口")
@Slf4j
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    @PostMapping("/login")
    @ApiOperation("微信登录")
    private Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) throws LoginException {
        log.info("微信用户登录:{}", userLoginDTO.getCode());
        User user = userService.wxLogin(userLoginDTO);


        //为微信生成令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .build();

        return Result.success(userLoginVO);


    }

    @GetMapping("/{id}")
    @ApiOperation("获取水质数据")
    public Result<ShipVO> getData(@PathVariable("id") Long id) {
       ShipVO shipVO = userService.getData(id);
        return Result.success(shipVO);
    }
}